<?php

namespace App\Http\Controllers\V1;

use Throwable;
use App\Traits\Eth;
use App\Support\Code;
use App\Support\Config;
use App\Models\EthRecord;
use App\Models\YecRecord;
use App\Support\Currency;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use App\Http\Resources\WithdrawCollection;

class WithdrawController extends ApiController
{
    use Eth;

    /**
     * @param  Request  $request
     * @return \Illuminate\Http\JsonResponse
     * @throws \App\Exceptions\ConfigNotSetException
     */
    public function store(Request $request)
    {
        $user = $this->getUser();
        $data = [
            'user_id' => $user->id,
            'value' => abs($request->value),
            'to_address_id' => $request->to_address_id
        ];

        if ($request->currency == Currency::ETH and $data['value'] < 0.05) {
            return $this->fail(Code::PARAMETER_ERROR, '提币金额必须大于 0.05');
        }

        if ($data['value'] > $user->getEnableValueByCurrency($request->currency)) {
            return $this->fail(Code::PARAMETER_ERROR, '余额不足');
        }

        $data['value'] = -$data['value']; // 放到数据库中的应该是负数

        if ($request->currency == Currency::YEC) {
            $data['enable_value'] = $data['value']; // todo 根据后台配置项设置
            $data['type'] = YecRecord::TYPE_WITHDRAW;
            try {
                DB::transaction(function () use ($data, $user, $request) {
                    $user->addFreezeByCurrency($request->currency, abs($data['value']));
                    YecRecord::create($data);
                });
            } catch (\Throwable $exception) {
                \Log::error("提币错误：{$data['to_address_id']}、{$data['value']}");
            }
        } elseif ($request->currency == Currency::ETH) {
            $data['enable_value'] = $data['value'] + 0.005; // todo 0.005 是手续费
            $data['type'] = EthRecord::TYPE_WITHDRAW;

            if (!Config::getEthEnabled()) {
                $data['from_address'] = $this->withdraw(
                    $data['to_address_id'], $data['enable_value']);
                $data['status'] = EthRecord::STATUS_CONFIRMED;
            } else {
                $data['status'] = EthRecord::STATUS_UNCONFIRMED;
            }

            try {
                DB::transaction(function () use ($data, $user, $request) {
                    $eth = EthRecord::create($data);
                    if (!Config::getEthEnabled()) {
                        $eth->record()->create([
                            'type' => '提币',
                            'value' => $eth->value,
                            'user_id' => $eth->user_id,
                            'currency' => Currency::ETH
                        ]);
                    } else {
                        $user->addFreezeByCurrency($request->currency, abs($data['value']));
                    }
                });
            } catch (Throwable $exception) {
                Log::error("提币错误：{$data['to_address_id']}、{$data['value']}");
            }
        }

        return $this->success();
    }

    public function index()
    {
        return $this->success(
            new WithdrawCollection(
                EthRecord::where('user_id', $this->getUser()->id)
                    ->where('type', EthRecord::TYPE_WITHDRAW)
                    ->orderByDesc('created_at')->paginate()
            )
        );
    }
}
